package it.hive.controller.download;

import it.hive.io.downloader.Downloader;
import it.hive.mediaplayer.beans.impl.Traccia;
import it.hive.model.Application;
import it.hive.model.common.ApplicationProperties;

import java.io.File;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.stage.DirectoryChooser;

import org.apache.commons.lang3.StringUtils;

public class DownloadGUI {

	public static void scaricaTraccia(Traccia traccia) {
		// percentualeDownload.setVisible(true);

		ApplicationProperties.downloadInCorso.set(true);
		ApplicationProperties.percentualeDownload.set(-1);
		// download.setVisible(false);
		// download.setDisable(true);
		File downloadDirectory = null;
		if (!ApplicationProperties.boolUsaSempreDefaultDownloadDirectory.get()) {
			DirectoryChooser directoryChooser = new DirectoryChooser();
			directoryChooser.setTitle("Salva file " + traccia.getTrackName());
			directoryChooser.setInitialDirectory(new File(System.getProperty("user.home")));
			downloadDirectory = directoryChooser.showDialog(null);
		} else {
			String path = ApplicationProperties.defaultDownloadDirectoryPath.get();
			downloadDirectory = new File(StringUtils.isEmpty(path) ? System.getProperty("user.home") : path);
		}
		if (downloadDirectory != null) {
			if (traccia.isUnparsed()) {
				Application.getIstanza().risolviURL(traccia);
			}
			Downloader fileDownloader = Application.getIstanza().downloadMP3File(traccia, downloadDirectory.getAbsolutePath());
			if (fileDownloader != null) {
				ApplicationProperties.percentualeDownload.bind(fileDownloader.progressProperty());
				ApplicationProperties.FrameTitle.bind(fileDownloader.messageProperty());

				fileDownloader.downloadCompletatoProperty().addListener(new ChangeListener<Boolean>() {
					@Override
					public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
						if (newValue) {
							ApplicationProperties.downloadInCorso.set(false);
							ApplicationProperties.percentualeDownload.unbind();
						}
					}
				});

				new Thread(fileDownloader).start();
			}
		} else {
			ApplicationProperties.downloadInCorso.set(false);
		}

	}

}
